﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace CivitaiCLI.Utils
{
    public class CivitaiWorkarounds
    {
        public class AutoNumberToStringConverter : JsonConverter<string>
        {
            //public override bool CanConvert(Type typeToConvert)
            //{
            //    return typeof(string) == typeToConvert;
            //}

            public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                if (reader.TokenType == JsonTokenType.Number)
                {
                    if(reader.TryGetInt64(out long l))
                    {
                        return l.ToString();
                    }
                    else if(reader.TryGetUInt64(out ulong u))
                    {
                        return u.ToString();
                    }
                    else if(reader.TryGetDouble(out double d))
                    {
                        return d.ToString();
                    }
                }
                if (reader.TokenType == JsonTokenType.String)
                {
                    return reader.GetString();
                }
                using (JsonDocument document = JsonDocument.ParseValue(ref reader))
                {
                    return document.RootElement.Clone().ToString();
                }
            }

            public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
            {
                writer.WriteStringValue(value.ToString());
            }
        }
    }
}
